const Controller = require("egg").Controller;

// 定义校验规则
const vCate = {
  catename: "string",
  catevalue: "string",
};

const vList = {
  pagesize: "number",
  pagenum: "number",
};

class CateController extends Controller {
  // 新增分类
  async create() {
    const { ctx, service } = this;
    ctx.validate(vCate, ctx.request.body);
    const check = await service.books.cate.checkCate(ctx.request.body);
    if (check) {
      return (ctx.body = ctx.fail("分类已存在"));
    }
    const res = await service.books.cate.create(ctx.request.body);
    if (res.affectedRows === 1) {
      ctx.body = ctx.success("新增分类成功");
    } else {
      ctx.body = ctx.fail("新增分类失败");
    }
  }
  // 删除分类
  async delete() {
    const { ctx, service } = this
    const res = await service.books.cate.delete(ctx.params)
    if(res.affectedRows === 1){
      ctx.body = ctx.success('删除分类成功')
    }else {
      ctx.body = ctx.fail('删除分类失败')
    }
  }
  // 修改分类
  async update() {
    const { ctx, service } = this
    ctx.validate({...vCate, cateid: 'string'}, ctx.request.body)
    const res = await service.books.cate.update(ctx.request.body)
    if(res.affectedRows === 1){
      ctx.body = ctx.success('修改分类成功')
    }else {
      ctx.body = ctx.fail('修改分类失败')
    }
  }
  // 查询分类(分页)
  async list() {
    const { ctx, service } = this;
    ctx.validate(vList, ctx.request.body);
    const res = await service.books.cate.list(ctx.request.body);
    ctx.body = ctx.list("获取分类列表成功", {
      data: res.data,
      total: res.total,
    });
  }
  // 查询分类(列表)
  async listselect(){
    const { ctx, service } = this;
    const res = await service.books.cate.listselect(ctx.request.body)
    ctx.body = ctx.success('获取分类列表成功', res)
  }
}

module.exports = CateController;
